package com.dongpl.module.system_user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.dongpl.module.system_user.dao.SystemUserMapper;
import com.dongpl.module.system_user.entity.SystemUserEntity;
import com.dongpl.module.system_user.model.SystemUser;
import com.dongpl.module.system_user.service.SystemUserService;
import com.dongpl.utils.SaltUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class SystemUserServiceImpl implements SystemUserService {

    @Resource
    private SystemUserMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean registerUser(SystemUser user) {
        SystemUserEntity entity = new SystemUserEntity();
        //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
        String simpleUUID = IdUtil.simpleUUID();
        entity.setUid(simpleUUID);
        // 1. 存放用户名
        entity.setUsername(user.getUsername());
        // 2.1 获取随机盐
        String salt = SaltUtil.getSalt(8);
        // 2.2 明文密码进行md5 + salt + hash散列
        // 2.3 将随机盐保存到数据
        entity.setSalt(salt);
        // 2.4 存放密码
        entity.setPassword(user.getPassword());
        // 3. 存放时间
        entity.setCreateTime(DateUtil.now());
        // 4. 状态值
        entity.setStatus(1);
        int insert = mapper.insert(entity);
        int count = mapper.insertDefaultRole(entity.getUid());
        return insert > 0 && count > 0;
    }
}
